package cz.data.common.database.datasource;

import cz.data.common.database.*;
import cz.data.common.support.db.DbProperty;
import cz.data.common.support.db.source.DataSourceFactory;
import cz.data.common.support.db.source.DbQuery;
import cz.data.common.support.db.DbType;
import cz.data.common.database.exception.DataQueryException;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

public class JdbcDataSourceFactory implements DataSourceFactory {

    @Override
    public DbQuery createDbQuery(DbProperty property) {
        property.valid();
        DbType dbType = DbType.getDbType(property.getDbType());
        DataSource dataSource = CacheDataSourceBean.createDataSource(property);
        return createDbQuery(dataSource, dbType);
    }

    public DbQuery createDbQuery(DataSource dataSource, DbType dbType) {
        DbDialect dbDialect = DialectFactory.getDialect(dbType);
        if (dbDialect == null) {
            throw new DataQueryException("该数据库类型正在开发中");
        }
        AbstractJdbcDbQuery dbQuery = new AbstractJdbcDbQuery();
        dbQuery.setDataSource(dataSource);
        dbQuery.setJdbcTemplate(new JdbcTemplate(dataSource));
        dbQuery.setDbDialect(dbDialect);
        return dbQuery;
    }

}
